package com.tang.lts.core.nio;

import com.tang.lts.core.nio.channel.ChannelInitializer;
import com.tang.lts.core.nio.config.NioServerConfig;
import com.tang.lts.core.nio.handler.NioHandler;
import com.tang.lts.core.nio.processor.NioProcessor;
import com.tang.lts.core.nio.processor.NioServerProcessor;

import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.channels.ServerSocketChannel;

/**
 * @author Tang
 * @classname NioServer
 * @description [  ]
 * @date 2022/5/12 11:33
 */
public class NioServer {

    private NioServerConfig serverConfig;

    private NioHandler eventHandler;

    private NioServerProcessor processor;

    public NioServer(NioServerConfig serverConfig, NioHandler nioHandler, ChannelInitializer channelInitializer) {
        setEventHandler(nioHandler);
        this.processor = new NioServerProcessor(serverConfig,nioHandler,channelInitializer);
    }

    private void setEventHandler(NioHandler eventHandler) {
        if (eventHandler == null) {
            eventHandler = null;
        }
        this.eventHandler = eventHandler;
    }

    public void bind(InetSocketAddress localAddress) {

        try {

            init();

            // 启动 selector
            this.processor.start();

            // 注册到selector
            this.processor.register();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init() throws SocketException {
        ServerSocketChannel channel = this.processor.javaChannel();
        if (this.serverConfig.getReceiveBufferSize() != null) {
            channel.socket().setReceiveBufferSize(this.serverConfig.getReceiveBufferSize());
        }
        if (this.serverConfig.getReuseAddress() != null) {
            channel.socket().setReuseAddress(this.serverConfig.getReuseAddress());
        }
    }
}